<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="navBar">
			<view class="left" @click="goBack">返回</view>
			<view class="center">发布新帖</view>
			<view class="right" @click="submitPost">发布</view>
		</view>

		<!-- 发布内容 -->
		<view class="postForm">
			<view class="inputGroup">
				<label for="title">标题</label>
				<input id="title" v-model="title" placeholder="请输入帖子标题" />
			</view>
			<view class="inputGroup">
				<label for="content">内容</label>
				<textarea id="content" v-model="content" placeholder="请输入帖子内容"></textarea>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			title: '',
			content: '',
			token: '',
			user: {}
		}
	},
	onLoad() {
		this.token = uni.getStorageSync("token");
		this.user = uni.getStorageSync("user");
	},
	methods: {
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		toIndex() {
			uni.reLaunch({
				url: '/pages/index/index',
			});
		},
		submitPost() {
			if (this.title.trim() === '' || this.content.trim() === '') {
				uni.showToast({
					icon: "none",
					title: "标题和内容不能为空"
				});
				return;
			}

			uni.showLoading({
				title: '发布中...'
			});
			
			const token = this.token;
			if(!token) {
				uni.showToast({
					icon: "none",
					title: '请先登录'
				});
				return;
			}
			
			// 发送请求到服务器以创建新帖子
			uni.request({
				url: "http://localhost:8080/addPost", // 替换为实际的API地址
				method: "POST",
				data: {
					userId:this.user.userId,
					title:this.title,
					content:this.content
				},
				header: {
					'Authorization': token,
					'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
				},
				success: (res) => {
					uni.hideLoading();
					if(res.data.code == 200) {
						uni.showToast({
							icon: "success",
							title: "发布成功"
						});
						setTimeout(() => {
							this.toIndex();
						}, 1500);
					} else {
						uni.showToast({
							icon: "none",
							title: "发布失败：" + res.data.msg || "未知错误"
						});
					}
				},
				fail: () => {
					uni.hideLoading();
					uni.showToast({
						icon: "none",
						title: "网络错误"
					});
				}
			});
		}
	}
}
</script>


<style scoped lang="scss">
.container {
	padding: 20rpx;

	.navBar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 80rpx;
		background-color: #1296db;
		color: white;
		padding: 0 30rpx;
		margin-bottom: 20rpx;

		.left, .right {
			font-size: 32rpx;
		}
		.center {
			font-weight: bold;
			font-size: 36rpx;
		}
	}

	.postForm {
		.inputGroup {
			margin-bottom: 20rpx;

			label {
				display: block;
				margin-bottom: 10rpx;
				font-size: 28rpx;
				color: #333;
			}

			input, textarea {
				width: 100%;
				border: 1rpx solid #ccc;
				border-radius: 5rpx;
				padding: 10rpx;
				box-sizing: border-box;
				font-size: 28rpx;
			}
			
			input {
				min-height: 50rpx;
			}

			textarea {
				min-height: 500rpx;
			}
		}
	}
}
</style>